<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表:优秀实践，copy domain修改列表-->
		<el-table :data="pageData.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="标识" width="100" sortable>
			</el-table-column>
			<el-table-column prop="name" label="名称" width="150" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="路径" width="120" sortable>
			</el-table-column>
			<!--<el-table-column prop="state" label="状态" width="120" sortable :formatter="stateFormatter">-->
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: blue" v-if="scope.row.state==0">正常</span>
					<span style="color: red" v-else="scope.row.state==-1">禁用</span>
				</template>
			</el-table-column>
			<!--private Employee manager;//管理员-->
			<!--private Department parent;//上级部门-->
			<el-table-column prop="manager.username" label="经理"  width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="120" sortable>
			</el-table-column>
			<el-table-column label="操作" min-width="120">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="query.currentPage" :page-size="query.pageSize" :total="pageData.total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
		    v-model="editFormVisible" 老版本打开对话框
		    ref="editForm"
		-->
		<el-dialog :title="title"  :visible.sync="departmentVisible" :close-on-click-modal="false">
			<el-form :model="department" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="department.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识" prop="sn">
					<el-input v-model="department.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="department.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="经理">
				<el-select v-model="department.manager" value-key="id" clearable placeholder="请选择">
					<el-option
							v-for="item in employee"
							:key="item.id"
							:label="item.username"
							:value="item">
						<span style="float: left">{{ item.username }}</span>
						<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
					</el-option>
				</el-select>
				</el-form-item>
				<el-form-item label="部门">
					<el-cascader
                            v-model="department.parent"
                            :options="deptTree"
							:props="{
							    checkStrictly: true,
							    label:'name',
                                value:'id'
							 }"
							clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentVisible = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    export default {
        data() {
            return {
                pageData:{
                    //分页条
                    total:0,
                    //数据表格
                    data:[]
                },
                query:{
                    // 搜索关键字
                    keyword:'',
                    //分页条
                    currentPage:1,
                    //分页条
                    pageSize:10
                },
				employee:{},
                deptTree:[],
				title:"",
				msg:'',
                listLoading: false,
                sels: [],//列表选中列

                departmentVisible: false,//编辑界面是否显示
                departmentLoading: false,
                departmentFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                department: {
                    id: null,
                    sn: '',
                    name: '',
                    dirPath: '',
					state: 0,
					manager:{},
                    parent: null
                }
            }
        },
        methods: {
            //状态显示转换-不能上色
            // stateFormatter: function (row, column) {
            //    if(row.state==0){
            //        return "正常"
            // 	}else{
            //        return "<font style='color: red;'>禁用</font>"
            // 	}
            // },
            search(){
                //修改页码
                this.query.currentPage =1;
                //改查询条件=双向绑定输入时自动改变
                this.getDepartments();
            },
            handleCurrentChange(val) {
                this.query.currentPage = val;
                this.getDepartments();
            },
            //获取用户列表
            getDepartments(){
            	//加载条
                this.listLoading = true;
                this.$http.post("/department",this.query)
                    .then(result => {
                        // debugger;
                        this.pageData = result.data;
                        console.debug(this.pageData);
                        //去除加载条
                        this.listLoading = false;
                    })
                    .catch(result=>{
                        alert("错了！");
                    })

            },
            //删除
            handleDel: function (index, row) {

                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(()=>{
                    // 开启加载图标
					this.listLoading = true;
					this.$http.delete("/department/"+row.id).then(result=>{
					    if (result.data.success){
                            this.$message({
                                message: "删除成功",
                                type: 'success'
                            });
						}else {
                            this.$message({
                                message:"删除失败",
                                type:'error'
                            })
						}
                        this.listLoading = false;
                        this.getDepartments();
					}).catch(result=>{
					    console.log(result)
					    alert("报错")
					})
				})
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.title = "编辑界面"
                this.departmentVisible = true;
                this.getEmployee();
                this.getDeptTree();
                this.department = Object.assign({}, row);
                // 获取路径
                let dirpath = row.dirPath;
                // 将后端的路径分为数组
                let dirpaths = dirpath.split("/");
                // 声明一个新数组来装数据
				let path = [];
				// 获取上级部门
                for(let i =1;i<dirpaths.length-1;i++){
                    // 将dirpaths中还是字符串的数据转为数字
                    path.push(parseInt(dirpaths[i]));
				}
				// 将数据交给department
				this.department.parent = path;
            },
            //显示新增界面
            handleAdd: function () {
                this.title = "新增界面"
                this.departmentVisible = true;
                this.getEmployee();
                this.getDeptTree();
                // 置空
                this.department = {
                    id: null,
                    sn: '',
                    name: '',
                    dirPath: '',
                    state: 0,
                    manager:{},
                    parent: null
                };
            },
            //编辑
            departmentSubmit: function () {
                this.$refs.departmentForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.departmentLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.department);
                            // 获取上级部门
                            let paraArr = para.parent;
                            if(paraArr){
                                para.parent = {"id":paraArr[paraArr.length-1]}
							}
							console.debug(para.parent);
							this.$http.put("/department",para)
								.then(result=>{
                                    this.departmentLoading = false;
								    if (result.data.success){
								        this.$message({
											message:"提交成功",
											type:"success"
										})
                                        this.departmentVisible = false; //关闭对话框
                                        this.$refs['departmentForm'].resetFields();//重置表单
                                        this.getDepartments(); //重新加载
									}else {
                                        this.$message({
                                            message:"提交失败",
                                            type:"error"
                                        })
									}

								})
                        }).catch(result=>{
                            console.debug(result)
							alert("报错")
						})
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/department",ids)
						.then(result=>{
						    if(result.data.success){
						        this.$message({
                                    message: "删除成功",
                                    type: 'success'
                                });
							}else {
                                this.$message({
                                    message: "删除失败",
                                    type: 'error'
                                });
							}
                            this.listLoading = false;
                            this.getDepartments();
							// 删除后跳到第一页
							this.handleCurrentChange(1);
						})
                }).catch(() => {
					alert("报错")
                });
            },
            getEmployee(){
                this.$http.get("/employee")
                    .then(result=>{
                        if(result){
                            console.debug(result.data)
                            this.employee = result.data
                        }
                    })
            },
            getDeptTree(){
                this.$http.get("/department/tree")
                    .then(result=>{
                        console.debug(result.data);
                        this.deptTree = result.data;
                    })
            }
        },
        mounted() {
            this.getDepartments();
        }
    }

</script>

<style scoped>

</style>